import router from "./router";
import store from "./store";
import NProgress from "nprogress"; // progress bar
import "nprogress/nprogress.css"; // progress bar style
import getPageTitle from "./utils/get-page-title";

NProgress.configure({ showSpinner: false }); // NProgress Configuration

/**
  鉴权路由规则
*/
router.beforeEach(async (to, _from, next) => {
  // start progress bar
  NProgress.start();

  // set page title
  document.title = getPageTitle(to.meta.title);

  // 是否已经登录
  const hasLogin = await store.dispatch("user/hasLogin");

  if (hasLogin) {
    // 已经登录就别去登录页面了
    if (to.path === "/login") {
      // if is logged in, redirect to the home page
      next({ path: "/" });
      NProgress.done(); // HACK: https://github.com/PanJiaChen/vue-element-admin/pull/2939
    } else {

      // 是否已经生成权限路由
      // 权限路由如果已经生成，长度不可能为0
      const hasGenerateRoutes = store.getters.permission_routes.length > 0;

      if (hasGenerateRoutes) {
        next();
      } else {
        // 是否已经获取了权限代码
        const hasPermissionCode = await store.dispatch("user/hasPermissionCode");
        if (hasPermissionCode === false) {
          // 没有权限代码，就获取一下
          await store.dispatch("user/getUserRoles");
        }

        // 拿到从服务器获取的菜单列表
        const menuList = store.getters.menuList;

        // 过滤出当前菜单权限可用的路由
        const accessRoutes = await store.dispatch(
          "permission/generateRoutes",
          menuList
        );

        // 将生成后的权限路由加入VueRouter
        // 页面每次刷新都会重新生成路由，路由不是持久化的，不过计算路由的开销比较小
        router.addRoutes(accessRoutes);

        // HACK: method to ensure that addRoutes is complete
        // set the replace: true, so the navigation will not leave a history record
        next({ ...to, replace: true });
      }
    }
  } else {

    // 目标是否是登录页面, 是的话就给过了.
    if (to.name === "Login") {
      next();
    } else {
      next({ name: "Login" });
    }
  }
});

router.afterEach(() => {
  // finish progress bar
  NProgress.done();
});
